<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <style>
      #container {
        width: 600px;
        height: 300px;
        overflow: hidden;
        border: 1px solid black;
        position: relative;
      }

      #ball {
        position: absolute;
        left: 0;
        top: 0;
        font-size: 2em;
        transform: 10s ease-in-out infinite;
      }
      #startButton {
        position: absolute;
        left: 260px;
        top: 10px;
      }
      #resetButton {
        position: absolute;
        left: 360px;
        top: 10px;
      }
    </style>
  </head>

  <body>
    <div id="container">
      <button id="startButton">开始动画</button>
      <button id="resetButton">恢复</button>
      <div id="ball">⚫</div>
    </div>
    <script type="text/javascript">
      const startBtn = document.querySelector('#startButton')
      const resetButton = document.querySelector('#resetButton')
      const ball = document.querySelector('#ball')

      startBtn.addEventListener('click', () => {
        test_ball()
        startBtn.disabled = true
      })
      resetButton.addEventListener('click', () => {
        ball.style.left = '0px'
        ball.style.top = '0px'
        startBtn.disabled = false
        clearInterval(timer)
      })
      let timer = null

      function test_ball() {
        let x = 0 // 水平位置
        let y = 0 // 垂直位置
        let vx = 10 // 水平速度 (px/s)
        let vy = 0 // 垂直速度 (px/s)
        let ay = 10 // 垂直加速度 (px/s²)
        let dt = 1000 / 60 // 时间间隔 (ms)

        timer = setInterval(function () {
          // 更新水平位置
          x += vx * (dt / 1000)

          // 更新垂直速度
          vy += ay * (dt / 1000)

          // 更新垂直位置
          y += vy * (dt / 1000)

          // 检查边界条件
          if (x >= container.offsetWidth - ball.offsetWidth) {
            x = container.offsetWidth - ball.offsetWidth
            vx = -vx // 反弹
          }
          if (y >= container.offsetHeight - ball.offsetHeight) {
            y = container.offsetHeight - ball.offsetHeight
            vy = -vy // 反弹
          }
          if (y <= 0) {
            y = 0
            vy = -vy // 反弹
          }

          // 设置小球位置
          ball.style.left = x + 'px'
          ball.style.top = y + 'px'
        }, dt)
      }
    </script>
  </body>
</html>
